package com.itheima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.admin.mapper.AdUserMapper;
import com.itheima.admin.pojo.AdUser;
import com.itheima.admin.service.AdUserService;
import com.itheima.common.util.JwtUtil;
import com.itheima.common.util.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * <p>
 * 管理员用户信息表 服务实现类
 * </p>
 *
 * @author 作者
 * @since 2021-08-19
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {

    @Autowired
    private AdUserMapper adUserMapper;

    /***
     * 登录
     *  1:name+password
     *  2:匹配密码：根据name查询AdUser
     *  3:获取AdUser.salt
     *  4:MD5(password+AdUser.salt)==AdUser.password?
     *  5:匹配成功，登录成功-颁发令牌
     *    匹配失败，登录失败
     */
    @Override
    public String login(AdUser adUser) {
        //1:根据name查询AdUser
        QueryWrapper<AdUser> queryWrapper = new QueryWrapper<AdUser>();
        queryWrapper.eq("name",adUser.getName());
        AdUser user = adUserMapper.selectOne(queryWrapper);
        if(user!=null){
            //2:获取AdUser.salt
            String salt = user.getSalt();
            //3:MD5(password+AdUser.salt)==AdUser.password?
            if(Md5Util.toMD5(adUser.getPassword(),salt).equals(user.getPassword())){
                //4:匹配成功，登录成功-颁发令牌
                //user->Map->JwtUtil->创建token令牌->密码清空
                user.setPassword("*");
                Map<String,Object> dataMap = BeanMap.create(user);
                return JwtUtil.create(dataMap);
            }
        }
        return null;
    }
}
